package com.boboPlanet.user.aspect;

import com.boboPlanet.comm.exception.BusinessException;
import com.boboPlanet.user.annotation.RedisLimit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description: TODO redis限流切面类
 * @Author: mis_wu
 * @Date: 2023/4/14
 * @Company xxx
 **/
@Aspect
@Component
@Slf4j
public class RedisLimitAspect {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private DefaultRedisScript<Long> redisScript;

    @PostConstruct
    public void init(){
        redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(Long.class);
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("config/RedisLimit.lua")));
    }

    @Pointcut("@annotation(com.boboPlanet.user.annotation.RedisLimit)")
    public void redisLimitPointcut() {}

    @Before("redisLimitPointcut()")
    public void doBefore(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        RedisLimit redisLimit = method.getAnnotation(RedisLimit.class);

        if (redisLimit != null){
            String key = redisLimit.key();
            String className = method.getDeclaringClass().getName();

            String limitKey = key + ":" + className + method.getName();
            log.info("redis limit key is: {}",limitKey);

            if (StringUtils.isBlank(key)){
                throw BusinessException.build("redis limit key cannot be null");
            }

            long second = redisLimit.limitReqSecond();
            long expire = redisLimit.expire();
            List<String> keys = new ArrayList<>();
            keys.add(key);

            Long count = stringRedisTemplate.execute(redisScript, keys, String.valueOf(second), String.valueOf(expire));


            if (count != null && count == 0){
                log.error("获取key失败,key is: {}",key);
                throw BusinessException.build(redisLimit.msg());
            }

        }

    }
}
